<template>
  <div class="order-apply-invoice">
    <div id="twoBar2Main" ref="chartContainer" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, watch, nextTick, ref, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'

interface ChartConfig {
  xAxisData: string[]
  yAxisNormalDataBar: number[]
  yAxisOverDataBar: number[]
}

const props = defineProps<{
  config: ChartConfig
}>()

const emits = defineEmits<{
  (e: 'barClick', params: any): void
}>()

const chartInstance = ref<echarts.ECharts | null>(null)
const chartContainer = ref<HTMLElement | null>(null)

// 计算属性确保响应式更新
const rawData = computed(() => [
  props.config.yAxisNormalDataBar,
  props.config.yAxisOverDataBar
])

const totalData = computed(() => {
  const result: number[] = []
  for (let i = 0; i < rawData.value[0].length; ++i) {
    let sum = 0
    for (let j = 0; j < rawData.value.length; ++j) {
      sum += rawData.value[j][i]
    }
    result.push(sum)
  }
  return result
})

const series = computed<echarts.BarSeriesOption[]>(() => {
  return ['normalUnReturnQty', 'overdueUnReturnQty'].map((name, sid) => ({
    name: name === 'normalUnReturnQty' ? '正常待还回调箱量' : '超期待还回调箱量',
    type: 'bar',
    stack: 'total',
    barWidth: '60%',
    label: {
      show: true,
      formatter: (params: any) => {
        const value = params.value as number
        return totalData.value[params.dataIndex] <= 0 
          ? '0' 
          : `${Math.round(value)}个`
      }
    },
    data: rawData.value[sid].map(
      (d, did) => 
      totalData.value[did] <= 0 ? 0 : d
    )
  }))
})

const chartOption = computed(() => ({
  legend: {
    right: '50px',
    top: '0',
    selectedMode: false
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: (value: number) => `${value * 100}%`
    }
  },
  xAxis: {
    type: 'category',
    data: Array.from(props.config.xAxisData)
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: (params: any) => {
      const [normal, overdue] = params as any[]
      const total = normal.value + overdue.value
      return `
        <div>${normal.axisValue}</div>
        <div>${normal.marker} ${normal.seriesName}: ${Math.round(normal.value * 1000) / 10}%</div>
        <div>${overdue.marker} ${overdue.seriesName}: ${Math.round(overdue.value * 1000) / 10}%</div>
        <div>总计: ${Math.round(total * 1000) / 10}%</div>
      `
    }
  },
  series: series.value
}))

const initChart = () => {
  if (!chartInstance.value && chartContainer.value) {
    chartInstance.value = echarts.init(chartContainer.value)

    // 添加点击事件监听
    chartInstance.value.on('click', 'series.bar', (params: any) => {
      emits('barClick', params)
    })
  }
  chartInstance.value?.setOption(chartOption.value)
}


watch(() => props.config, () => {
  nextTick(() => {
    initChart()
  })
}, { deep: true })

onMounted(() => {
  nextTick(initChart)
})

onBeforeUnmount(() => {
  if (chartInstance.value) {
    // 移除事件监听
    chartInstance.value.off('click', 'series.bar')
    chartInstance.value.dispose()
    chartInstance.value = null
  }
})
</script>

<style lang="scss" scoped>
.order-apply-invoice {
  width: 100%;
  height: 100%;
}
</style>